package com.example.onlinemusic.Controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.Binding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {

    @Value("${music.local.path}")
    String SAVE_PATH;
    @Autowired
    MusicMapper musicMapper;
    @Autowired
    LoveMusicMapper loveMusicMapper;

    /**
     * 上传音乐
     * @param singer
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request, HttpServletResponse response){
        //是否登录
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            log.info("没有登录");
            return new ResponseBodyMessage<>(-1, "请登陆后上传",false);
        }
        String filename = file.getOriginalFilename();
        //上传的歌曲是否相同
        String s = filename.substring(0, filename.indexOf("."));
        Music music = musicMapper.selectByName(s, singer);
        if(music != null)
            return new ResponseBodyMessage<>(-1, "有重复的歌曲",false);
        //上传音月
        String path = SAVE_PATH + "/" + filename;
        System.out.println(path);
        File dest = new File(path);
        if(!dest.exists()){
            dest.mkdirs();
        }
        try{
            file.transferTo(dest);
            //return new ResponseBodyMessage<>(200, "上传成功", true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "文件上传失败",false);
        }

        //上传进数据库
        int idx = filename.lastIndexOf(".");
        String title = filename.substring(0, idx);

        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();

        String url = "/music/get?path="+title;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());

        try{
            int res = musicMapper.insert(title,singer,time,url,userid);
            if(res == 1){
                response.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(200, "数据库上传成功", true);
            }else{
                return new ResponseBodyMessage<>(-1, "数据库上传失败",false);
            }
        }catch (BindingException | IOException e){
            dest.delete();
            return new ResponseBodyMessage<>(-1, "数据库上传失败",false);
        }
    }

    /**
     * 获取歌曲的字节
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(SAVE_PATH+"/"+path);
        byte[] res = null;
        try{
            res = Files.readAllBytes(file.toPath());
            if(res == null){
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除单个服务器，数据库中的音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(String id){
        int id1 = Integer.parseInt(id);//musicId
        Music music = musicMapper.selectById(id1);
        if(music == null){
            return new ResponseBodyMessage<>(-1,"没有该音乐",false);
        }
        int res = musicMapper.deleteMusicById(id1);
        if(res == 1){
            String filename = music.getTitle();
            File file = new File(SAVE_PATH+"/"+filename+".mp3");
            if(file.delete()){
                loveMusicMapper.deleteLoveMusicById(id1);
                return new ResponseBodyMessage<>(200,"服务器删除成功",true);
            }
            return new ResponseBodyMessage<>(-1,"服务器删除失败",false);
        }else {
            return new ResponseBodyMessage<>(-1,"数据库删除失败",false);
        }
    }

    /**
     * 删除多个音乐
     * @param id
     * @return
     */
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id){
        int sum = 0;
        for(int i : id){//i : musicId
            Music music = musicMapper.selectById(i);
            if(music == null){
                return new ResponseBodyMessage<>(-1,"没有查找到该元素",false);
            }
            int res = musicMapper.deleteMusicById(i);
            if(res == 1){
                String filename = music.getTitle();
                File file = new File(SAVE_PATH+"/"+filename+".mp3");
                if(file.delete()){
                    sum += res;
                    loveMusicMapper.deleteLoveMusicById(i);
                    //return new ResponseBodyMessage<>(200,"服务器删除成功",true);
                }else {
                    return new ResponseBodyMessage<>(-1, "服务器删除失败", false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库删除失败",false);
            }
        }
        if(sum == id.size()){
            return new ResponseBodyMessage<>(200, "删除成功",true);
        }
        return new ResponseBodyMessage<>(-1,"删除失败",false);
    }

    /**
     * 根据歌名模糊查找
     * @param musicName
     * @return
     */
    @RequestMapping("/findMusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> res = null;
        if(musicName != null){
            res = musicMapper.findMusicByName(musicName);
        }else {
            res = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(200, "查询到了",res);
    }
}
